<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>练习4</title>
</head>

<body>

</body>
<script>
    //1.求斐波那契数列Fibonacci中的第n个数是多少？      1 1 2 3 5 8 13 21...
    function fib(n) {
        if (n == 1 || n == 2) return 1;
        return fib(n - 1) + fib(n - 2);
    }
    console.log(fib(12));

    //2.输入一个年份，判断是否是闰年[闰年：能被4整数并且不能被100整数，或者能被400整数]
    function isLeapYear(year) {
        if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) {
            return "闰年";
        } else {
            return "平年";
        }
    }
    console.log(`2020年是${isLeapYear(2020)}`);
    console.log(`2023年是${isLeapYear(2023)}`);

    //3.和电脑猜拳10次(电脑出拳用随机数)，显示每次结果，最后累计输赢平局结果
    function game() {
        let win = 0;
        let lose = 0;
        let draw = 0;
        let choice = ['剪刀', '石头', '布'];

        for (let round = 1; round <= 10; round++) {
            let computerNum = Math.floor(Math.random() * 3);

            let flag = false;
            let userNum;

            while (!flag) {
                let userInput = prompt(`第${round}轮 - 请输入你的选择（剪刀、石头、布）:`);

                if (userInput === null) {
                    alert('游戏已取消');
                    return;
                }

                let userChoiceIndex = choice.indexOf(userInput.trim());

                if (userChoiceIndex !== -1) {
                    userNum = userChoiceIndex;
                    flag = true;
                } else {
                    alert('输入无效，请重新输入剪刀、石头或布！');
                }
            }

            let result;
            if (userNum == computerNum) {
                result = '平局';
                draw++;
            } else if (
                (userNum == 0 && computerNum == 2) ||
                (userNum == 1 && computerNum == 0) ||
                (userNum == 2 && computerNum == 1)
            ) {
                result = '你赢';
                win++;
            } else {
                result = '电脑赢';
                lose++;
            }

            alert(`第${round}轮结果:\n你出 ${choice[userNum]}，电脑出 ${choice[computerNum]}\n${result}`);
        }

        alert(`游戏结束！\n最终结果：\n赢 ${win} 次\n输 ${lose} 次\n平局 ${draw} 次`);
    }

    game();
</script>

</html>